using ZXing.Net.Maui;

namespace MauiBuilder.Views;

/// <summary>
/// 扫码页面
/// </summary>
public partial class BarcodeScanPage : ContentPage
{
    private bool _isFlashlightOn = false;
    private TaskCompletionSource<BarcodeResult?> _scanTaskSource;

    /// <summary>
    /// 构造函数
    /// </summary>
    public BarcodeScanPage()
    {
        InitializeComponent();
        _scanTaskSource = new TaskCompletionSource<BarcodeResult?>();
    }

    /// <summary>
    /// 等待扫码结果的异步方法
    /// </summary>
    /// <returns>扫码结果</returns>
    public Task<BarcodeResult?> WaitForScanResultAsync()
    {
        return _scanTaskSource.Task;
    }

    /// <summary>
    /// 检测到条码时的事件处理
    /// </summary>
    /// <param name="sender">事件发送者</param>
    /// <param name="e">条码检测事件参数</param>
    private void OnBarcodesDetected(object sender, BarcodeDetectionEventArgs e)
    {
        var barcode = e.Results?.FirstOrDefault();
        if (barcode != null)
        {
            // 停止检测
            CameraView.IsDetecting = false;
            
            // 设置扫码结果并关闭页面
            MainThread.BeginInvokeOnMainThread(async () =>
            {
                _scanTaskSource.SetResult(barcode);
                await Shell.Current.GoToAsync("..");
            });
        }
    }

    /// <summary>
    /// 闪光灯按钮点击事件
    /// </summary>
    /// <param name="sender">事件发送者</param>
    /// <param name="e">事件参数</param>
    private void OnFlashlightClicked(object sender, EventArgs e)
    {
        try
        {
            _isFlashlightOn = !_isFlashlightOn;
            CameraView.IsTorchOn = _isFlashlightOn;
            
            FlashlightButton.Text = _isFlashlightOn ? "🔦 关闭闪光灯" : "🔦 开启闪光灯";
        }
        catch (Exception ex)
        {
            DisplayAlert("错误", $"闪光灯控制失败：{ex.Message}", "确定");
        }
    }

    /// <summary>
    /// 取消按钮点击事件
    /// </summary>
    /// <param name="sender">事件发送者</param>
    /// <param name="e">事件参数</param>
    private void OnCancelClicked(object sender, EventArgs e)
    {
        // 停止检测
        CameraView.IsDetecting = false;
        
        // 设置取消结果并关闭页面
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            _scanTaskSource.SetResult(null);
            await Shell.Current.GoToAsync("..");
        });
    }

    /// <summary>
    /// 页面出现时
    /// </summary>
    protected override void OnAppearing()
    {
        base.OnAppearing();
        
        // 开始检测
        CameraView.IsDetecting = true;
    }

    /// <summary>
    /// 页面消失时
    /// </summary>
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        
        // 停止检测并关闭闪光灯
        CameraView.IsDetecting = false;
        if (_isFlashlightOn)
        {
            CameraView.IsTorchOn = false;
            _isFlashlightOn = false;
        }
        
        // 如果任务还没有完成，设置为取消
        if (!_scanTaskSource.Task.IsCompleted)
        {
            _scanTaskSource.SetResult(null);
        }
    }
}